package com.lemon.boot.common.interceptor;

import com.lemon.boot.common.utils.ResponseUtil;
import com.lemon.boot.common.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

/**
 * @author 李猛
 * @datetime 2024/2/28 18:55
 * @description Security权限拦截器
 */
@Slf4j
public class SecurityMethodInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("SecurityMethodInterceptor.preHandle.uri:{}", request.getRequestURI());
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //1.获取增强的类上的注解
            Annotation[] classAnnotations = handlerMethod.getBeanType().getAnnotations();
            if (classAnnotations.length > 0 && SecurityUtil.isSecurityAnnotated(classAnnotations)) {
                return true;
            }

            //2.获取增强方法上的注解
            Annotation[] methodAnnotations = handlerMethod.getMethod().getAnnotations();
            if (methodAnnotations.length > 0 && SecurityUtil.isSecurityAnnotated(methodAnnotations)) {
                return true;
            }
        }

        //3.权限判断
        boolean match = SecurityUtil.hasPermission(SecurityUtil.getAuthentication(), SecurityUtil.toPermission(request.getRequestURI()));
        if (match) {
            return true;
        } else {
            ResponseUtil.fail(response, HttpStatus.FORBIDDEN.value(), "未授权操作！");
            return false;
        }
    }

    /**
     * 拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求完成的拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
